import { ref } from "vue";
import myCookies from "@/utils/myCookies";
// 模拟消息数据
const messages = ref([
    {
        content: "你好呀！",
        isOwn: false,
        time: new Date("2024-03-20 09:00"),
    },
]);


const ws = ref();
const message = ref({
    toUserId: 32, // 必须是数字类型
    content: "你好", // 字符串类型
    time: new Date(),
});

const token = myCookies.getToken();
// 初始化 WebSocket 连接
export function initWebSocket() {
    if (token != undefined) {
        ws.value = new WebSocket(
            `ws://localhost:7000/chat?token=${encodeURIComponent(token)}`
        ); // 替换为你的 WebSocket 地址
    }

    // 监听连接打开
    ws.value.onopen = () => {
        console.log("WebSocket 连接已建立");
    };

    // 监听消息接收
    ws.value.onmessage = (event: any) => {
        const eventData = JSON.parse(event.data);
        console.log(eventData);
        messages.value.push({
            content: eventData.data,
            isOwn: false,
            time: eventData.time,
        });
    };

    // 监听错误
    ws.value.onerror = (error: any) => {
        console.error("WebSocket 错误:", error);
    };

    // 监听连接关闭
    ws.value.onclose = () => {
        console.log("WebSocket 连接已关闭");
    };
};
//发送消息
export function sendMessage() {
    ws.value.send(JSON.stringify(message.value));
    messages.value.push({
        content: message.value.content,
        isOwn: true,
        time: new Date(),
    });
    message.value.content = "";
}

